package aspectjlib.logging;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import aspectjlib.enums.CurrentAspect;

public class MasterTracker {
	private final Logger logger = Logger.getLogger(MasterTracker.class.getName());
	private Map<Long,ThreadTracker> threads = new HashMap<Long,ThreadTracker>();
	private long initialTime = -1;
	private CurrentAspect cae;

	private static MasterTracker mt;

	public static MasterTracker getMt(CurrentAspect cae) {
		if (mt == null)
			mt = new MasterTracker(cae);
		return mt;
	}

	private MasterTracker(CurrentAspect cae) {
		PropertyConfigurator.configure("config/log4j.properties");
		this.cae = cae;
		switch (this.cae) {
		case TIMER:
			logger.debug("FunctionId,ThreadId,NanoTime,Runtime");
			break;
		case METHODTOUCHES:
			logger.debug("FunctionId,ThreadId,Uses");
			break;
		}
	}

	public void startTimer(String functionId) {
		Long time = System.nanoTime();
		Long threadId = Thread.currentThread().getId();
		if (initialTime == -1) {
			initialTime = time;
		}
		if (!threads.containsKey(threadId)) {
			threads.put(threadId, new ThreadTracker(functionId, time, cae));
		}
		else {
			threads.get(threadId).add(functionId, time);
		}
		if (cae.equals(CurrentAspect.TIMER))
			logger.debug(functionId + "," + threadId + "," + (time - initialTime) + "," + 0);
	}

	public void endTimer(String functionId, Long time) {
		Long threadId = Thread.currentThread().getId();
		Long starttime = threads.get(threadId).remove();
		if (cae.equals(CurrentAspect.TIMER))
			logger.debug(functionId + "," + threadId + "," + (time - initialTime) + "," + (time - starttime));

	}
}